import { defineStore } from 'pinia';
import { fetchUserInfo, login } from '@/apis/sys/user';
import { store } from '@/store';

export const useUserStore = defineStore({
  id: 'app-user-store',
  state: (): UserStore => {
    return {
      token: null,
      uuid: null,
      name: null,
      username: null,
      info: null,
      // user info
      userInfo: null,
      tenantId: null,
      productId: null,
      appid: null, // 增加appId
      permission: null,
      permissionCodeMap: [],
    };
  },
  getters: {
    getToken(state) {
      return state.token;
    },
    getUid(state) {
      return state.uuid;
    },
    getName(state) {
      return state.name;
    },
    getUserInfo(state) {
      return state.userInfo;
    },
    getAppid(state) {
      return state.appid;
    },
    getProductId(state) {
      return state.productId;
    },
    getPermission(state) {
      return state.permission
    },
    getPermissionCodeMap(state) {
      return state.permissionCodeMap
    },
  },
  actions: {
    login(loginForm: LoginForm): Promise<LoginResponse> {
      return new Promise((resolve, reject) => {
        login(loginForm)
          .then(async resp => {
            this.token = resp.token;
            this.uuid = resp.uuid;
            // 调用API获取信息
            const userInfo = await fetchUserInfo();
            if (userInfo) {
              const { userItem, resourcesItems } = userInfo;
              this.setUserInfo(userItem);
              this.buildPermissionInfo(resourcesItems)
            }
            resolve(resp);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    logout() {
      this.token = null;
      this.uuid = null;
      this.name = null;
    },
    setToken(token: string, uid: string) {
      this.token = token;
      this.uuid = uid;
      // 将数据持久化到LocalStorage中，用于兼容旧数据
      uni.setStorageSync(
        'al__Access-Token',
        JSON.stringify({
          value: token,
          expire: new Date().getTime() + 8 * 60 * 60 * 1000
        })
      );
      uni.setStorageSync(
        'al__UID',
        JSON.stringify({
          value: uid,
          expire: new Date().getTime() + 8 * 60 * 60 * 1000
        })
      );
    },
    setProductId(productId) {
      this.productId = productId;
    },
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo;
      if (!userInfo) {
        // TODO: clean info
        return;
      }
      const { id, username, email, gender, mobile, name, tenantId } = userInfo;
      // @ts-ignore
      this.info = { id, username, email, gender, mobile, name, tenantId };
      this.username = username;
      this.name = name ? name : null;
    },
    buildPermissionInfo(permission: UserPermissionInfo[]) {
      this.permission = permission
      if (!permission) {
          return
      }
      // 转换成字符串并用正则提取处code，避免递归
      const permissionCodeArr = JSON.stringify(permission).match(/"code":"(.+?)"/g)
      const permissionCodePure =
          permissionCodeArr?.map(item => {
              const codeStr = item.match(/"code":"(.+?)"/)
              return codeStr && codeStr.length > 0 ? codeStr[1] : ''
          }) || []
      // 增加权限码映射表，避免递归查找
      this.permissionCodeMap = Array.from(new Set(permissionCodePure))
      // 保存缓存数据
      uni.setStorageSync('permissionCodeMap', JSON.stringify(this.permissionCodeMap));
    },
  },
  persist: {
    enabled: true,
    strategies: [{ storage: localStorage, paths: ['token', 'uuid', 'productId', 'tenantId', 'appid', 'userInfo'] }]
  }
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
